<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2022-04-21
 * Time: 15:26:31
 * Info:
 */

namespace app\admin\controller;

use support\Request;
use app\common\model\Admin as AdminModel;
use app\common\model\LoginLog as LoginLogModel;
use Gregwar\Captcha\CaptchaBuilder;
use think\facade\Cache;
use xianrenqh\Dingxiang\CaptchaClient;

class LoginController extends CommonController
{

    protected $validate;

    /*public function __construct()
    {
        parent::__construct();
    }*/

    /**
     * 该方法会在请求前调用
     */
    public function beforeAction(Request $request)
    {
        $adminId = session('session_admin_id');
        if ( ! empty($adminId)) {
            //return redirect('index');
            return $this->success('您已登录，无需再次登录', '', '', "/admin/index");
        }
    }

    public function index()
    {
        $login_captcha = get_config('login_captcha');
        $dx_appId      = get_config('dingxiang_appid');
        $dx_apiurl     = get_config('dingxiang_apiurl');

        return view('login', ['login_captcha' => $login_captcha, 'dx_appId' => $dx_appId, 'dx_apiurl' => $dx_apiurl]);
    }

    public function check_login(Request $request)
    {
        $login_captcha = get_config('login_captcha');
        $param         = $request->all();

        $this->validate->rule([
            'username|用户名' => 'require',
            'password|密码'  => 'require',
        ]);
        $this->validate->message([
            'username.require' => '登录名不能为空',
            'password.require' => '密码不能为空',
        ]);
        if ( ! $this->validate->check($param)) {
            return error_json($this->validate->getError());
        }

        //普通验证码
        $uniqid = '';
        if ($login_captcha == 1) {
            $captcha = ! empty($param['captcha']) ? $param['captcha'] : '';
            if (empty($captcha)) {
                return error_json('验证码不能为空');
            }
            $uniqid = ! empty($param['uniqid']) ? $param['uniqid'] : '';
            if (empty($uniqid)) {
                return error_json('uniqid不能为空');
            }
            // 对比session中的captcha值
            if (strtolower($captcha) !== strtolower(Cache::get('captcha_'.$uniqid))) {
                return error_json('验证码不正确或已失效');
            }
        }

        //顶象验证码
        if ($login_captcha == 2) {
            $appId     = get_config('dingxiang_appid');
            $appSecret = get_config('dingxiang_appSecret');
            $dx_apiurl = get_config('dingxiang_apiurl');

            if (empty($appId || empty($appSecret))) {
                return error_json('顶象验证的密钥不能为空');
            }
            $captcha_token = ! empty($param['captcha_token']) ? $param['captcha_token'] : '';

            $client = new CaptchaClient($appId, $appSecret);
            $client->setTimeOut(2);
            $client->setCaptchaUrl($dx_apiurl."/api/tokenVerify");
            $response = $client->verifyToken($captcha_token);
            if ( ! $response->result) {
                return error_json('验证失败');
            }
        }

        //写入登陆日志表
        $get_client_ip = get_client_ip();
        $loginDevice   = [
            'ip_address' => $get_client_ip,
            'country'    => getIpToArea($get_client_ip)['country'],
            'area'       => getIpToArea($get_client_ip)['province'],
            'city'       => getIpToArea($get_client_ip)['city'],
            'isp'        => getIpToArea($get_client_ip)['isp'],
        ];

        $adminInfo = AdminModel::where('username', $param['username'])->find();
        if (empty($adminInfo)) {
            //写入登陆日志
            $loginDevice['desc']      = 'error：用户名不存在'.json_encode([
                    'username' => $param['username'],
                    'password' => $param['password']
                ]);
            $loginDevice['user_id']   = 0;
            $loginDevice['user_name'] = $param['username'];
            LoginLogModel::addRecord($loginDevice);

            return error_json('用户名或密码不正确！');
        }
        $password = cmf_password($param['password'], $adminInfo['salt']);
        if ($password != $adminInfo['password']) {
            //写入登陆日志
            $loginDevice['desc']      = 'error：密码不正确'.json_encode([
                    'username' => $param['username'],
                    'password' => $param['password']
                ]);
            $loginDevice['user_id']   = $adminInfo['id'];
            $loginDevice['user_name'] = $param['username'];
            LoginLogModel::addRecord($loginDevice);

            return error_json('用户名或密码不正确！！！');
        }

        if ($adminInfo['status'] != 1) {
            //写入登陆日志
            $loginDevice['desc']      = 'error：该账号已被禁用'.json_encode([
                    'username' => $param['username'],
                    'password' => '******'
                ]);
            $loginDevice['user_id']   = $adminInfo['id'];
            $loginDevice['user_name'] = $param['username'];
            LoginLogModel::addRecord($loginDevice);

            return error_json('该账号已被禁用');
        }

        //登录成功
        Cache::delete('captcha_'.$uniqid);

        $token  = $this->createToken($adminInfo['id']);
        $result = $this->updateTokenExpire($token, $adminInfo['id']);
        if ( ! $result) {
            return error_json("登录失败!");
        }
        $this->adminId = $adminInfo['id'];
        session()->set('session_admin_id', $adminInfo['id']);
        session()->set('admin_info_'.$adminInfo['id'], $adminInfo);

        AdminModel::manageEdit([
            'id'        => $adminInfo['id'],
            'logintime' => time(),
            'loginip'   => get_client_ip(),
            'token'     => $token
        ]);

        //写入登陆日志
        $loginDevice['desc']      = 'success：登陆成功'.json_encode([
                'username' => $param['username'],
                'password' => '******'
            ]);
        $loginDevice['user_id']   = $adminInfo['id'];
        $loginDevice['user_name'] = $adminInfo['username'];

        LoginLogModel::addRecord($loginDevice);

        return $this->success("登录成功!", ['token' => $token, 'admin_info' => $adminInfo]);

    }

    /**
     * 输出验证码图像
     */
    public function showCaptcha(Request $request, $id)
    {
        // 初始化验证码类
        $builder = new CaptchaBuilder;
        // 生成验证码
        $builder->build();
        // 将验证码的值存储到session中
        //$request->session()->set('captcha_'.$id, strtolower($builder->getPhrase()));
        //将验证码存入cache
        Cache::set('captcha_'.$id, strtolower($builder->getPhrase()), 60);
        // 获得验证码图片二进制数据
        $img_content = $builder->get();

        // 输出验证码二进制数据
        return response($img_content, 200, ['Content-Type' => 'image/jpeg']);
    }

    public function captcha()
    {
        $uniqid = uniqid((string)mt_rand(100000, 999999));
        $src    = route('login/show_captcha', ['id' => $uniqid]);
        $data   = [
            'src'    => $src,
            'uniqid' => $uniqid,
        ];

        return $this->success("ok", $data);
    }

}
